package com.dragon.mmochat.service;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_1_7S;
import com.dragon.mmochat.message.Mmochat_5_10C;
import com.dragon.mmochat.message.Mmochat_5_10S;
import com.dragon.mmochat.message.Mmochat_5_11C;
import com.dragon.mmochat.message.Mmochat_5_13C;
import com.dragon.mmochat.message.Mmochat_5_14C;
import com.dragon.mmochat.message.Mmochat_5_14S;
import com.dragon.mmochat.message.Mmochat_5_19C;
import com.dragon.mmochat.message.Mmochat_5_1S;
import com.dragon.mmochat.message.Mmochat_5_20C;
import com.dragon.mmochat.message.Mmochat_5_25C;
import com.dragon.mmochat.message.Mmochat_5_26C;
import com.dragon.mmochat.message.Mmochat_5_28C;
import com.dragon.mmochat.message.Mmochat_5_30C;
import com.dragon.mmochat.model.enumType.MmochatDrugType;
import com.dragon.mmochat.model.enumType.MmochatEquipAttributeType;
import com.dragon.mmochat.model.enumType.MmochatEquipPlaceType;
import com.dragon.mmochat.model.enumType.MmochatEquipType;
import com.dragon.mmochat.model.enumType.MmochatFamilyType;
import com.dragon.mmochat.model.enumType.MmochatMaterialType;
import com.dragon.mmochat.model.enumType.MmochatObjOwnerState;
import com.dragon.mmochat.model.enumType.MmochatPetStateType;
import com.dragon.mmochat.model.enumType.MmochatPetType;
import com.dragon.mmochat.model.enumType.MmochatPropType;
import com.dragon.mmochat.model.enumType.MmochatPropUsingRoleType;
import com.dragon.mmochat.model.enumType.MmochatRoleAttributeType;
import com.dragon.mmochat.model.enumType.MmochatRoleBmpType;
import com.dragon.mmochat.model.enumType.MmochatRoleType;
import com.dragon.mmochat.model.enumType.MmochatServerType;
import com.dragon.mmochat.model.enumType.MmochatSkillType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.object.MmochatCommonObject;
import com.dragon.mmochat.model.object.MmochatDrug;
import com.dragon.mmochat.model.object.MmochatPackageGrid;
import com.dragon.mmochat.model.object.MmochatProp;
import com.dragon.mmochat.model.role.MmochatMonster;
import com.dragon.mmochat.model.role.MmochatPet;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.model.skill.MmochatSkill;
import com.dragon.mmochat.util.CreateTlvWin;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.message.SkymobiProtocolMessage;
import com.skymobi.message.widget.AddDataTLV;
import com.skymobi.message.widget.ClearDataTLV;
import com.skymobi.message.widget.CloseWinTLV;
import com.skymobi.message.widget.CreateMsgBoxTLV;
import com.skymobi.message.widget.SendDataTLV;
import com.skymobi.message.widget.ShowWaitingMsgBoxTLV;
import com.skymobi.message.widget.TLVStructure;
import com.skymobi.message.widget.WinType;
import com.skymobi.service.SkymobiService;
import com.skymobi.util.Text;

public class MmochatPetService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatPetService.class);

	// 1-220怪物战斗属性:等级--><属性类别-->属性值>
	public static Map<Integer, Map<MmochatRoleAttributeType, Double>> monsterBaseAttackData = new ConcurrentHashMap<Integer, Map<MmochatRoleAttributeType, Double>>();
	// 怪物基本属性:类型-->带基本属性的怪
	public static Map<MmochatRoleType, MmochatMonster> monsterBaseAttrData = new ConcurrentHashMap<MmochatRoleType, MmochatMonster>();

	public MmochatPetService() {
		if (!MmochatMain.openMergeServer) {
			/* 怪物NPC属性.txt: 1-220级怪物战斗属性,包含物攻,法攻,速度,气血 */
			log.debug("开始装载怪物战斗属性...");
			monsterBaseAttackData.clear();
			File file = new File("base/monsterAttr.txt");
			int level = 1;
			if (file.exists()) {
				if (file.isFile()) {
					try {
						BufferedReader reader = new BufferedReader(
								new FileReader(file));
						String lineBuf;
						while ((lineBuf = reader.readLine()) != null) {
							String[] array = lineBuf.split("\t");
							if (array == null || array.length == 0) {
								throw new RuntimeException("怪物属性.txt第" + level
										+ "级数据不完整,请重启!!");
							}
							Map<MmochatRoleAttributeType, Double> data = new ConcurrentHashMap<MmochatRoleAttributeType, Double>();
							try {
								level = Integer.parseInt(array[0].trim());
								data.put(MmochatRoleAttributeType.杀死怪物经验,
										(double) Integer.parseInt(array[1]
												.trim()));
								data.put(MmochatRoleAttributeType.怪物金钱掉落,
										(double) Integer.parseInt(array[2]
												.trim()));
								data.put(MmochatRoleAttributeType.物伤,
										(double) Integer.parseInt(array[3]
												.trim()));
								data.put(MmochatRoleAttributeType.法伤,
										(double) Integer.parseInt(array[4]
												.trim()));
								data.put(MmochatRoleAttributeType.物防,
										(double) Integer.parseInt(array[5]
												.trim()));
								data.put(MmochatRoleAttributeType.法防,
										(double) Integer.parseInt(array[6]
												.trim()));
								data.put(MmochatRoleAttributeType.气血,
										(double) Integer.parseInt(array[7]
												.trim()));
								data.put(MmochatRoleAttributeType.法力,
										(double) Integer.parseInt(array[8]
												.trim()));
								data.put(MmochatRoleAttributeType.速度,
										(double) Integer.parseInt(array[9]
												.trim()));
								data.put(MmochatRoleAttributeType.物理闪避,
										(double) Integer.parseInt(array[10]
												.trim()));
								data.put(MmochatRoleAttributeType.法术闪避,
										(double) Integer.parseInt(array[11]
												.trim()));
								data.put(MmochatRoleAttributeType.物理暴击,
										(double) Integer.parseInt(array[12]
												.trim()));
								data.put(MmochatRoleAttributeType.法术暴击,
										(double) Integer.parseInt(array[13]
												.trim()));
								data.put(MmochatRoleAttributeType.物理暴击抵抗,
										(double) Integer.parseInt(array[14]
												.trim()));
								data.put(MmochatRoleAttributeType.法术暴击抵抗,
										(double) Integer.parseInt(array[15]
												.trim()));
								data.put(MmochatRoleAttributeType.物理致命一击,
										(double) Integer.parseInt(array[16]
												.trim()));
								data.put(MmochatRoleAttributeType.法术致命一击,
										(double) Integer.parseInt(array[17]
												.trim()));
								data.put(MmochatRoleAttributeType.物理致命抵抗,
										(double) Integer.parseInt(array[18]
												.trim()));
								data.put(MmochatRoleAttributeType.法术致命抵抗,
										(double) Integer.parseInt(array[19]
												.trim()));
								data.put(MmochatRoleAttributeType.物理破防,
										(double) Integer.parseInt(array[20]
												.trim()));
								data.put(MmochatRoleAttributeType.法术破防,
										(double) Integer.parseInt(array[21]
												.trim()));
								data.put(MmochatRoleAttributeType.封印抵抗,
										(double) Integer.parseInt(array[22]
												.trim()));
								data.put(MmochatRoleAttributeType.冰冻抵抗,
										(double) Integer.parseInt(array[23]
												.trim()));
								data.put(MmochatRoleAttributeType.混乱抵抗,
										(double) Integer.parseInt(array[24]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视封印抵抗,
										(double) Integer.parseInt(array[25]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视冰冻抵抗,
										(double) Integer.parseInt(array[26]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视混乱抵抗,
										(double) Integer.parseInt(array[27]
												.trim()));
								data.put(MmochatRoleAttributeType.强化封印,
										(double) Integer.parseInt(array[28]
												.trim()));
								data.put(MmochatRoleAttributeType.强化冰冻,
										(double) Integer.parseInt(array[29]
												.trim()));
								data.put(MmochatRoleAttributeType.强化混乱,
										(double) Integer.parseInt(array[30]
												.trim()));
								data.put(MmochatRoleAttributeType.物理免疫,
										(double) Integer.parseInt(array[31]
												.trim()));
								data.put(MmochatRoleAttributeType.法术免疫,
										(double) Integer.parseInt(array[32]
												.trim()));
								data.put(MmochatRoleAttributeType.抗雷,
										(double) Integer.parseInt(array[33]
												.trim()));
								data.put(MmochatRoleAttributeType.抗水,
										(double) Integer.parseInt(array[34]
												.trim()));
								data.put(MmochatRoleAttributeType.抗毒,
										(double) Integer.parseInt(array[35]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视抗雷,
										(double) Integer.parseInt(array[36]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视抗水,
										(double) Integer.parseInt(array[37]
												.trim()));
								data.put(MmochatRoleAttributeType.忽视抗毒,
										(double) Integer.parseInt(array[38]
												.trim()));
								data.put(MmochatRoleAttributeType.神圣物理伤害,
										(double) Integer.parseInt(array[39]
												.trim()));
								data.put(MmochatRoleAttributeType.神圣法术伤害,
										(double) Integer.parseInt(array[40]
												.trim()));
								data.put(MmochatRoleAttributeType.道行倍数, Double
										.parseDouble(array[41].trim()));
							} catch (NumberFormatException e) {
								e.printStackTrace();
								throw new RuntimeException("怪物属性.txt第" + level
										+ "级数据有非数字,请重启!!");
							}
							monsterBaseAttackData.put(level, data);
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
						throw new RuntimeException("怪物NPC属性.txt缺失,请重启!!");
					} catch (IOException e) {
						e.printStackTrace();
						throw new RuntimeException("怪物NPC属性.txt读取出错,请重启!!");
					}
				} else {
					throw new RuntimeException("怪物NPC属性.txt缺失,请重启!!");
				}
			} else {
				throw new RuntimeException("怪物NPC属性.txt缺失,请重启!!");
			}
			log.debug("怪物战斗属性装载成功!级别数=" + level);

			/* monster.xml: 怪物基本属性,包含成长值,怪物材料掉落，怪物等级，所在地图 */
			log.debug("开始装载基本怪物属性...");
			monsterBaseAttrData.clear();
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder;
			try {
				docBuilder = docBuilderFactory.newDocumentBuilder();
				Document doc;
				doc = docBuilder.parse(new File("base/monster.xml"));
				doc.getDocumentElement().normalize();
				NodeList listOfMonster = doc.getElementsByTagName("monster");
				log.debug("monster num = " + listOfMonster.getLength());

				for (int s = 0; s < listOfMonster.getLength(); s++) {
					log.debug("开始加载第" + (s + 1) + "个怪物基本信息");
					Node firstMonsterNode = listOfMonster.item(s);
					if (firstMonsterNode.getNodeType() == Node.ELEMENT_NODE) {
						Element firstMonsterElement = (Element) firstMonsterNode;
						MmochatMonster monster;
						// 读取level
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("level");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物等级不是数字,怪物level=" + num);
							}
							monster = new MmochatMonster(num);
						}
						// 读取type
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("type");
							if (nodeList.getLength() > 0) {
								String str = nodeList.item(0).getChildNodes()
										.item(0).getNodeValue().trim();
								monster.setPetType(MmochatPetType.valueOf(str));
							} else {
								monster.setPetType(MmochatPetType.野生);
							}
						}
						// 读取roleType
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("name");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							monster.setRoleType(MmochatRoleType.valueOf(str));
						}
						// 读取mapId
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("mapId");
							if (nodeList.getLength() > 0) {
								String str = nodeList.item(0).getChildNodes()
										.item(0).getNodeValue().trim();
								int num = 0;
								try {
									num = Integer.parseInt(str.trim());
								} catch (Exception e) {
									e.printStackTrace();
									throw new RuntimeException(
											"装载基本怪物时，怪物所在地图不是数字,怪物="
													+ monster.getName());
								}
								MmochatMap map = MmochatMapService
										.getMapByMapId(num);
								if (map != null) {
									map.getMonster().add(monster);
								} else {
									throw new RuntimeException(
											"装载基本怪物时没找到地图,mapId=" + num);
								}
							}
						}
						// 读取bmp
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("bmp");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							monster.setBmpType(MmochatRoleBmpType.valueOf(str));
						}
						// 读取family
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("family");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							monster.setFamily(MmochatFamilyType.valueOf(str));
						}
						// 读取可掉落材料
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("material");
							for (int j = 0; j < nodeList.getLength(); j++) {
								String str = nodeList.item(j).getChildNodes()
										.item(0).getNodeValue().trim();
								MmochatMaterialType type = MmochatMaterialType
										.valueOf(str);
								if (type != null) {
									monster.addMaterial(type);
								}
							}
						}
						// 读取物攻成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("pAttack");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物物攻成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setPhysicalAttack_protential(num);
						}
						// 读取法攻成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("mAttack");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物法攻成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setMagicAttack_protential(num);
						}
						// 读取物防成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("pDefence");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物物防成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setPhysicalDefend_protential(num);
						}
						// 读取法防成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("mDefence");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物法防成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setMagicDefend_protential(num);
						}
						// 读取血量成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("blood");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物血量成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setBlood_protential(num);
						}
						// 读取速度成长
						{
							NodeList nodeList = firstMonsterElement
									.getElementsByTagName("speed");
							String str = nodeList.item(0).getChildNodes().item(
									0).getNodeValue().trim();
							int num = 0;
							try {
								num = Integer.parseInt(str.trim());
							} catch (Exception e) {
								e.printStackTrace();
								throw new RuntimeException(
										"装载基本怪物时，怪物速度成长不是数字,怪物="
												+ monster.getName());
							}
							monster.setSpeed_protential(num);
						}

						// 装载战斗属性
						Map<MmochatRoleAttributeType, Double> attMap = monsterBaseAttackData
								.get(monster.getLevel());
						if (attMap == null) {
							throw new RuntimeException("装载基本怪物时，怪物战斗属性没有找到,怪物="
									+ monster.getName());
						}
						int dao = (int) (attMap
								.get(MmochatRoleAttributeType.道行倍数) * MmochatBattleService
								.getStandardDao(monster.getLevel(), 0));
						monster.setDao(dao);
						monster.setKillExp((int) ((double) attMap
								.get(MmochatRoleAttributeType.杀死怪物经验)));
						monster.setKillSmallMoney((int) ((double) attMap
								.get(MmochatRoleAttributeType.怪物金钱掉落)));
						monster.setPhysicalAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.物伤)));
						monster.setSpritAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.法伤)));
						monster.setPhysicalDefend((int) ((double) attMap
								.get(MmochatRoleAttributeType.物防)));
						monster.setMagicDefend((int) ((double) attMap
								.get(MmochatRoleAttributeType.法防)));
						monster.setTotalBlood((int) ((double) attMap
								.get(MmochatRoleAttributeType.气血)));
						monster.setSpeed((int) ((double) attMap
								.get(MmochatRoleAttributeType.速度)));
						monster.setPhysicalAvoid((int) ((double) attMap
								.get(MmochatRoleAttributeType.物理闪避)));
						monster.setMagicAvoid((int) ((double) attMap
								.get(MmochatRoleAttributeType.法术闪避)));
						monster.setPhysicalDeadlyAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.物理暴击)));
						monster.setMagicDeadlyAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.法术暴击)));
						monster
								.setPhysicalDeadlyAttackDefend((int) ((double) attMap
										.get(MmochatRoleAttributeType.物理暴击抵抗)));
						monster
								.setMagicDeadlyAttackDefend((int) ((double) attMap
										.get(MmochatRoleAttributeType.法术暴击抵抗)));
						monster.setPhysicalDoubleAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.物理致命一击)));
						monster.setMagicDoubleAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.法术致命一击)));
						monster
								.setPhysicalDoubleAttackDefend((int) ((double) attMap
										.get(MmochatRoleAttributeType.物理致命抵抗)));
						monster
								.setMagicDoubleAttackDefend((int) ((double) attMap
										.get(MmochatRoleAttributeType.法术致命抵抗)));
						monster.setPhysicalDefendIgnore((int) ((double) attMap
								.get(MmochatRoleAttributeType.物理破防)));
						monster.setMagicDefendIgnore((int) ((double) attMap
								.get(MmochatRoleAttributeType.法术破防)));
						monster.setAntiSeal((int) ((double) attMap
								.get(MmochatRoleAttributeType.封印抵抗)));
						monster.setAntiFreeze((int) ((double) attMap
								.get(MmochatRoleAttributeType.冰冻抵抗)));
						monster.setAntiConfuse((int) ((double) attMap
								.get(MmochatRoleAttributeType.混乱抵抗)));
						monster.setIgnoreAntiSeal((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视封印抵抗)));
						monster.setIgnoreAntiFreeze((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视冰冻抵抗)));
						monster.setIgnoreAntiConfuse((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视混乱抵抗)));
						monster.setStrengthenSeal((int) ((double) attMap
								.get(MmochatRoleAttributeType.强化封印)));
						monster.setStrengthenFreeze((int) ((double) attMap
								.get(MmochatRoleAttributeType.强化冰冻)));
						monster.setStrengthenConfuse((int) ((double) attMap
								.get(MmochatRoleAttributeType.强化混乱)));
						monster.setPhysicalDefendPercent((int) ((double) attMap
								.get(MmochatRoleAttributeType.物理免疫)));
						monster.setMagicDefendPercent((int) ((double) attMap
								.get(MmochatRoleAttributeType.法术免疫)));
						monster.setAntiGodSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.抗雷)));
						monster.setAntiHumanSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.抗水)));
						monster.setAntiDevilSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.抗毒)));
						monster.setIgnoreAntiGodSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视抗雷)));
						monster.setIgnoreAntiHumanSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视抗水)));
						monster.setIgnoreAntiDevilSkill((int) ((double) attMap
								.get(MmochatRoleAttributeType.忽视抗毒)));
						monster.setSuperPhysicalAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.神圣物理伤害)));
						monster.setSuperSpritAttack((int) ((double) attMap
								.get(MmochatRoleAttributeType.神圣法术伤害)));

						monsterBaseAttrData.put(monster.getRoleType(), monster);
					}
				}
			} catch (SAXException e1) {
				e1.printStackTrace();
				throw new RuntimeException("装载基本怪物属性失败,请重启!");
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new RuntimeException("装载基本怪物属性失败,请重启!");
			} catch (ParserConfigurationException e1) {
				e1.printStackTrace();
				throw new RuntimeException("装载基本怪物属性失败,请重启!");
			} catch (Exception e1) {
				e1.printStackTrace();
				throw new RuntimeException("装载基本怪物属性失败,请重启!");
			}

			log.debug("基本怪物属性装载完毕!");

		}
	}

	// 按等级、数量获取怪物经验
	public static int getMonsterExpByLevel(int level, int monsterNum) {
		Map<MmochatRoleAttributeType, Double> attrMap = monsterBaseAttackData
				.get(level);
		if (attrMap != null) {
			return (int) (attrMap.get(MmochatRoleAttributeType.杀死怪物经验) * monsterNum);
		}
		return 0;
	}

	public static int getMonsterExpByLevel(MmochatPlayer me, int monsterNum) {
		Map<MmochatRoleAttributeType, Double> attrMap = monsterBaseAttackData
				.get(me.getTrueLevel());
		if (attrMap != null) {
			return (int) (attrMap.get(MmochatRoleAttributeType.杀死怪物经验) * monsterNum);
		}
		return 0;
	}

	// 设置宠物随机成长(取[最大成长-min]到[最大成长-max]范围内随机值)
	public static void setRandPetGrown(MmochatMonster monster, MmochatPet pet,
			int min, int max) {
		if (monster == null || pet == null) {
			return;
		}
		int delta = MmochatUtil.getRandomValue(min, max);
		pet.setPhysicalAttack_protential(Math.max(0, monster
				.getPhysicalAttack_protential()
				- delta));

		delta = MmochatUtil.getRandomValue(min, max);
		pet.setMagicAttack_protential(Math.max(0, monster
				.getMagicAttack_protential()
				- delta));

		delta = MmochatUtil.getRandomValue(min, max);
		pet.setSpeed_protential(Math.max(0, monster.getSpeed_protential()
				- delta));

		delta = MmochatUtil.getRandomValue(min, max);
		pet.setBlood_protential(Math.max(0, monster.getBlood_protential()
				- delta));

		delta = MmochatUtil.getRandomValue(min, max);
		pet.setPhysicalDefend_protential(Math.max(0, monster
				.getPhysicalDefend_protential()
				- delta));

		delta = MmochatUtil.getRandomValue(min, max);
		pet.setMagicDefend_protential(Math.max(0, monster
				.getMagicDefend_protential()
				- delta));
	}

	// 设置宠物随机成长(取[最大成长-min]到[最大成长-max]范围内随机值)
	// type:0:物攻；1:法攻；2:速度；3:血量；4:物防；5:法防
	public static void setRandPetGrown(MmochatMonster monster, MmochatPet pet,
			int min, int max, int type) {
		if (monster == null || pet == null) {
			return;
		}
		int delta;
		switch (type) {
		case 0:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setPhysicalAttack_protential(Math.max(0, monster
					.getPhysicalAttack_protential()
					- delta));
			break;
		case 1:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setMagicAttack_protential(Math.max(0, monster
					.getMagicAttack_protential()
					- delta));
			break;
		case 2:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setSpeed_protential(Math.max(0, monster.getSpeed_protential()
					- delta));
			break;
		case 3:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setBlood_protential(Math.max(0, monster.getBlood_protential()
					- delta));
			break;
		case 4:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setPhysicalDefend_protential(Math.max(0, monster
					.getPhysicalDefend_protential()
					- delta));
			break;
		case 5:
			delta = MmochatUtil.getRandomValue(min, max);
			pet.setMagicDefend_protential(Math.max(0, monster
					.getMagicDefend_protential()
					- delta));
			break;
		default:
			break;
		}
	}

	// 由怪生成一个宠,isBaby=false,则生成野生宠(下限为满成长-30，上限为满成长-15);
	// isBaby = true则生成宝宝宠(下限为满成长-15，上限为满成长)，且等级归0
	public static MmochatPet createPetFromMonster(MmochatMonster monster,
			boolean isBaby) {
		MmochatPet pet = new MmochatPet(monster.getLevel());
		pet.setRoleType(monster.getRoleType());
		pet.setFamily(monster.getFamily());
		pet.setBmpType(monster.getBmpType());
		if (!isBaby) {
			// 直接捕捉到的野生宠物，属性点随机分配
			int level = monster.getLevel();
			pet.setLevel(level);
			pet.setPetType(monster.getPetType());
			setRandPetGrown(monster, pet, 15, 30);
			int randPoint = level * 2;
			int p1 = 0, p2 = 0, p3 = 0, p4 = 0;
			if (randPoint > 0) {
				p1 = MmochatUtil.getRandomValue(randPoint);
				randPoint -= p1;
			}
			p2 = randPoint;

			randPoint = level * 2;
			if (randPoint > 0) {
				p3 = MmochatUtil.getRandomValue(randPoint);
				randPoint -= p3;
			}
			p4 = randPoint;

			pet.setAttack_point(p1 + level);
			pet.setSprit_point(p2 + level);
			pet.setBlood_point(p3 + level);
			pet.setSpeed_point(p4 + level);
			pet.setSpace_point(0);
			// 根据等级配置技能
			if (level >= MmochatConstant.monsterSkill1LevelNeed) {
				MmochatSkillType skillType = null;
				switch (pet.getFamily()) {
				case 阐教:
					skillType = MmochatSkillType.雷电交加;
					break;
				case 人教:
					skillType = MmochatSkillType.寒冰利剑;
					break;
				case 截教:
					skillType = MmochatSkillType.焚心蚀骨;
					break;
				default:
					break;
				}
				if (skillType != null) {
					if (pet.getSkills().get(skillType) == null) {
						MmochatSkill skill = new MmochatSkill();
						skill.setType(skillType);
						pet.getSkills().put(skillType, skill);
					}
				}
			}
			if (level >= MmochatConstant.monsterSkill2LevelNeed) {
				MmochatSkillType skillType = null;
				switch (pet.getFamily()) {
				case 阐教:
					skillType = MmochatSkillType.飞云掣电;
					break;
				case 人教:
					skillType = MmochatSkillType.水漫金山;
					break;
				case 截教:
					skillType = MmochatSkillType.毒龙双飞;
					break;
				default:
					break;
				}
				if (skillType != null) {
					if (pet.getSkills().get(skillType) == null) {
						MmochatSkill skill = new MmochatSkill();
						skill.setType(skillType);
						pet.getSkills().put(skillType, skill);
					}
				}
			}
		} else {
			// 将野生洗成宝宝
			pet.setLevel(0);
			pet.setPetType(MmochatPetType.宝宝);
			setRandPetGrown(monster, pet, 0, 15);
		}

		pet.setCurBlood(pet.getTotalBlood());
		pet.setCurSprit(pet.getTotalSprit());
		return pet;
	}

	// 使用道具，生成(满成长-10)到满成长; 等级武学归0
	public static void createPetFromPet(MmochatPet pet) {
		MmochatMonster monster = monsterBaseAttrData.get(pet.getRoleType());
		setRandPetGrown(monster, pet, 0, 10);
		pet.setLevel(0);
		if (pet.getPetType() == MmochatPetType.野生) {
			pet.setPetType(MmochatPetType.宝宝);
		}
		pet.setBlood_point(0);
		pet.setSprit_point(0);
		pet.setAttack_point(0);
		pet.setSpeed_point(0);
		pet.setSpace_point(0);
		pet.setExp(0);
		pet.setDao(0);
		pet.getSkills().clear();
		pet.setCurBlood(pet.getTotalBlood());
		pet.setCurSprit(pet.getTotalSprit());
		pet.setLife_turn(0);
	}

	// 使用道具，生成(满成长-10)到满成长; 等级武学不归0
	public static void resetPetProtential(MmochatPet pet) {
		MmochatMonster monster = monsterBaseAttrData.get(pet.getRoleType());
		setRandPetGrown(monster, pet, 0, 10);
		pet.setCurBlood(pet.getTotalBlood());
		pet.setCurSprit(pet.getTotalSprit());
	}

	// 使用道具，生成(满成长-10)到满成长; 等级武学不归0
	// type:0:物攻；1:法攻；2:速度；3:血量；4:物防；5:法防
	public static void resetPetProtential(MmochatPet pet, int type) {
		MmochatMonster monster = monsterBaseAttrData.get(pet.getRoleType());
		setRandPetGrown(monster, pet, 0, 10, type);
		pet.setCurBlood(pet.getTotalBlood());
		pet.setCurSprit(pet.getTotalSprit());
	}

	// 获得满成长宠物
	public static MmochatPet createPetByType(MmochatRoleType roleType) {
		MmochatMonster monster = monsterBaseAttrData.get(roleType);
		MmochatPet pet = new MmochatPet(monster.getLevel());
		setRandPetGrown(monster, pet, 0, 0);
		pet.setLevel(0);
		pet.setRoleType(monster.getRoleType());
		pet.setFamily(monster.getFamily());
		pet.setBmpType(monster.getBmpType());
		pet.setPetType(monster.getPetType());
		pet.setCurBlood(pet.getTotalBlood());
		pet.setCurSprit(pet.getTotalSprit());
		return pet;
	}

	// 5.11设置宠物参战/休息
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_11(SkymobiHandler handler,
			Mmochat_5_11C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}

		MmochatPet pet = me.getPets().get(req.getPetId());
		if (pet == null) {
			return MmochatUtil.msgbox(req.getHallState(), "没有找到此宠物的相关信息!");
		}
		// TODO:宠物其它状态的判断
		if (req.getState() == 1) {
			// 设置参战
			if (pet.getState() == MmochatPetStateType.参战
					|| pet.getState() == MmochatPetStateType.替补) {
				return null;
			} else if (pet.getState() == MmochatPetStateType.休息) {
				if (pet.getLevel() > me.getLevel()
						+ MmochatConstant.maxPetLevelMoreThanOwner) {
					Mmochat_5_10S pack1 = new Mmochat_5_10S();
					pack1.setReset(true);
					pack1.setPets(new ArrayList<MmochatPet>(me.getPets()
							.values()));
					MmochatUtil.sendCommonPack(me, pack1);

					Mmochat_1_7S pack = new Mmochat_1_7S();
					pack.setMe(me);
					MmochatUtil.sendCommonPack(me, pack);
					// 宠物高于人物等级
					return MmochatUtil.msgbox(req.getHallState(), "此宠物等级超过您"
							+ MmochatConstant.maxPetLevelMoreThanOwner
							+ "级以上，您无法驾驭它!");
				}
				if (pet.getLife_turn() > me.getLife_turn()) {
					Mmochat_5_10S pack1 = new Mmochat_5_10S();
					pack1.setReset(true);
					pack1.setPets(new ArrayList<MmochatPet>(me.getPets()
							.values()));
					MmochatUtil.sendCommonPack(me, pack1);

					Mmochat_1_7S pack = new Mmochat_1_7S();
					pack.setMe(me);
					MmochatUtil.sendCommonPack(me, pack);
					// 宠物高于人物等级
					return MmochatUtil.msgbox(req.getHallState(),
							"此宠物的转生次数超过您的转生次数，您无法驾驭它!");
				}
				MmochatPet pkPet = me.getPkPet();
				MmochatPet bakPet = me.getBakPkPet();// 替补宠
				if (pkPet == null) {
					// 如果没有参战宠
					pet.setState(MmochatPetStateType.参战);
					if (bakPet != null) {
						Mmochat_5_10S pack1 = new Mmochat_5_10S();
						pack1.setReset(true);
						pack1.setPets(new ArrayList<MmochatPet>(me.getPets()
								.values()));
						MmochatUtil.sendCommonPack(me, pack1);
					}
				} else {
					// 如果有参战宠
					// 设置为替补
					if (bakPet != null) {
						bakPet.setState(MmochatPetStateType.休息);
					}
					pet.setState(MmochatPetStateType.替补);

					Mmochat_5_10S pack1 = new Mmochat_5_10S();
					pack1.setReset(true);
					pack1.setPets(new ArrayList<MmochatPet>(me.getPets()
							.values()));
					MmochatUtil.sendCommonPack(me, pack1);
				}
			}
		} else {
			// 设置休息
			if (pet.getState() == MmochatPetStateType.休息) {
				return null;
			} else {
				if (pet.getState() == MmochatPetStateType.替补) {
					pet.setState(MmochatPetStateType.休息);
					Mmochat_5_10S pack1 = new Mmochat_5_10S();
					pack1.setReset(true);
					pack1.setPets(new ArrayList<MmochatPet>(me.getPets()
							.values()));
					MmochatUtil.sendCommonPack(me, pack1);
				} else {
					pet.setState(MmochatPetStateType.休息);
				}
			}
		}
		// 更新头像信息
		Mmochat_1_7S pack = new Mmochat_1_7S();
		pack.setMe(me);
		return pack;
	}

	// 5.13 宠物加点
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_13(SkymobiHandler handler,
			Mmochat_5_13C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			// 在其它服，不处理
			return MmochatUtil.msgbox(req.getHallState(), "当前位于跨服区，无法进行此操作!");
		}
		MmochatPet pet = me.getPets().get(req.getPetId());
		if (pet == null) {
			return MmochatUtil.msgbox(req.getHallState(), "没有找到此宠物!");
		}
		synchronized (pet) {
			int num = Math.min(pet.getSpace_point(), req.getNum());
			if (num <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "没有可分配的属性点!");
			}
			switch (req.getPoint_type()) {
			case 0:
				pet.setASpacePointToAttack(num);
				break;
			case 1:
				pet.setASpacePointToSprit(num);
				break;
			case 2:
				pet.setASpacePointToBlood(num);
				break;
			case 3:
				pet.setASpacePointToSpeed(num);
				break;
			default:
				break;
			}
		}
		try {
			MmochatDao.updateRolePets(me);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Mmochat_5_10S pack = new Mmochat_5_10S();
		pack.addPet(pet);
		return pack;
	}

	// 5.14 丟弃宠物
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_14(SkymobiHandler handler,
			Mmochat_5_14C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			// 在其它服，不处理
			return MmochatUtil.msgbox(req.getHallState(), "当前位于跨服区，无法进行此操作!");
		}
		if (MmochatNpcService.checkStorePwd(me)) {
			return null;
		}
		MmochatPet pet = me.getPets().get(req.getPetId());
		if (pet == null) {
			return MmochatUtil.msgbox(req.getHallState(), "没有找到此宠物的相关信息!");
		}
		if (pet.getOwnerState() != MmochatObjOwnerState.未认主) {
			return MmochatUtil.msgbox(req.getHallState(), "此宠物尚在<认主>状态，无法遗弃!");
		}
		if (pet.getBorrowFromRoleId() != null) {
			return MmochatUtil.msgbox(req.getHallState(), "此宠物是借来的，无法遗弃!");
		}
		// TODO:宠物其它状态的判断
		if (pet.getState() == MmochatPetStateType.参战
				|| pet.getState() == MmochatPetStateType.替补) {
			return MmochatUtil.msgbox(req.getHallState(), "当前宠物处于参战状态,无法遗弃!");
		}
		if (!pet.getName().equals(pet.getRoleType().toString())) {
			return MmochatUtil.msgbox(req.getHallState(),
					"当前宠物已改名,无法遗弃!请先将宠物名改回"
							+ MmochatUtil.wrapColor(pet.getRoleType()
									.toString(), Color.yellow));
		}
		// 删除宠物
		me.delPet(req.getPetId());
		try {
			MmochatDao.updateRolePets(me);
		} catch (Exception e) {
			e.printStackTrace();
			return MmochatUtil.msgbox(req.getHallState(), "数据库忙,请稍候再试!");
		}
		Mmochat_5_14S pack = new Mmochat_5_14S();
		pack.setDelPetId(req.getPetId());
		return pack;
	}

	// 5.10查看宠物信息
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_10(SkymobiHandler handler,
			Mmochat_5_10C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return null;
		}

		Mmochat_5_10S pack = new Mmochat_5_10S();
		pack.setReset(true);
		pack.setPets(new ArrayList<MmochatPet>(me.getPets().values()));
		return pack;
	}

	// 5.19 修改宠物名
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_19(SkymobiHandler handler,
			Mmochat_5_19C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			// 在其它服，不处理
			return MmochatUtil.msgbox(req.getHallState(), "当前位于跨服区，无法进行此操作!");
		}
		MmochatPet pet = me.getPets().get(req.getPetId());
		if (pet == null) {
			return MmochatUtil.msgbox(req.getHallState(), "没有找到此宠物的相关信息!");
		}
		String newName = req.getNewName();
		if (pet.getName().equals(newName)) {
			return MmochatUtil.msgbox(req.getHallState(), "修改成功!");
		}
		if (newName.length() < 1 || newName.length() > 4) {
			return MmochatUtil.msgbox(req.getHallState(), "宠物名为1到4个字!");
		}
		// 更新宠物名
		String oldName = pet.getName();
		pet.setName(newName);
		try {
			MmochatDao.updateRolePets(me);
		} catch (Exception e) {
			e.printStackTrace();
			pet.setName(oldName);
			return MmochatUtil.msgbox(req.getHallState(), "数据库忙,请稍候再试!");
		}
		Mmochat_5_10S pack = new Mmochat_5_10S();
		pack.addPet(pet);
		return pack;
	}

	// 给宠吃物品
	@SkymobiService
	public SkymobiProtocolMessage handleC_5_30(SkymobiHandler handler,
			Mmochat_5_30C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (MmochatMain.serverType == MmochatServerType.跨服战服务器) {
			// 在其它服，不处理
			return MmochatUtil.msgbox(req.getHallState(), "当前位于跨服区，无法进行此操作!");
		}
		MmochatPet pet = me.getPets().get(req.getPetId());
		if (pet == null) {
			return MmochatUtil.msgbox(req.getHallState(), "没有找到此宠物!");
		}
		MmochatPackageGrid grid = me.getMyPackage().get(req.getGridId());
		if (grid == null || !grid.isCanUse() || grid.getObject() == null) {
			return null;
		}
		MmochatCommonObject obj = grid.getObject();
		if (obj == null) {
			return null;
		}
		switch (obj.getObjectType()) {
		case 药品: {
			if (obj.getOverlapNum() <= 0) {
				grid.setObject(null);
				// 下发更新包裹数据
				Mmochat_5_1S pack = new Mmochat_5_1S();
				pack.addGrid(grid);
				MmochatUtil.sendCommonPack(me, pack);
				return null;
			}
			MmochatDrugType type = obj.getDrugType();
			if (type.getBlood() <= 0 && type.getSprit() <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "此药品无法食用!");
			}
			boolean used = false;
			if (type.getBlood() > 0) {
				// 补血
				if (pet.getCurBlood() < pet.getTotalBlood()) {
					pet.addCurBlood(type.getBlood());
					used = true;
				}
			}
			if (type.getSprit() > 0) {
				// 补蓝
				if (pet.getCurSprit() < pet.getTotalSprit()) {
					pet.addCurSprit(type.getSprit());
					used = true;
				}
			}
			if (!used) {
				return MmochatUtil.msgbox(req.getHallState(), "当前状态良好,无需食用此药!");
			}
			obj.delOverlapNum(1);
			if (obj.isUsedOut()) {
				grid.setObject(null);
			}

			// 更新药品和人气血状态
			try {
				MmochatDao.updateRoleAfterEatDrug(me);
			} catch (Exception e) {
				e.printStackTrace();
				return MmochatUtil.msgbox(req.getHallState(), "当前数据库忙,请稍候再试!");
			}
			// 更新人物头像信息
			Mmochat_1_7S pack = new Mmochat_1_7S();
			pack.setMe(me);
			MmochatUtil.sendCommonPack(me, pack);

			// 更新包裹格子
			Mmochat_5_1S pack2 = new Mmochat_5_1S();
			pack2.addGrid(grid);
			MmochatUtil.sendCommonPack(me, pack2);

			// 更新宠物
			Mmochat_5_10S pack1 = new Mmochat_5_10S();
			pack1.addPet(pet);
			return pack1;
		}
		case 装备: {
			break;
		}
		case 道具: {
			// 使用道具
			Map<Integer, Object> msg = MmochatPropService.useProp(me, req
					.getGridId(), pet);
			String errMsg = (String) msg.get(0);
			String successMsg = (String) msg.get(1);
			TLVStructure propTlv = (TLVStructure) msg.get(2);
			Boolean ret = (Boolean) msg.get(3);

			if (ret != null) {
				return null;
			}

			if (errMsg != null) {
				return MmochatUtil.msgbox(req.getHallState(), errMsg);
			}

			Mmochat_5_10S pack1 = new Mmochat_5_10S();
			pack1.addPet(pet);
			MmochatUtil.sendCommonPack(me, pack1);

			if (propTlv != null) {
				return MmochatUtil.tlvResponse(req.getHallState(), propTlv);
			} else {
				CreateMsgBoxTLV msgbox = new CreateMsgBoxTLV();
				if (successMsg == null) {
					successMsg = "使用成功!";
				}
				msgbox.setContent(new Text(successMsg));
				msgbox.setLeftName("确定");
				return MmochatUtil.tlvResponse(req.getHallState(), msgbox);
			}
		}
		default:
			break;
		}
		return MmochatUtil.msgbox(req.getHallState(), "此物品无法给宠物食用!");
	}
}
